function marg_damages=calc_marg_damages4(MargDamagesHour, TractSunlightProfile, ResProd)

global  ntract tract_nerc_xxwalk line_losses_loc alpha1LL alpha2LL demand


marg_damages=zeros(ntract,1);

for t_i=1:ntract
      
      n_i=tract_nerc_xxwalk(t_i);
      
      MargDamagesHourTract=MargDamagesHour(:,n_i)';
      
      marg_damages(t_i,1)=sum(-MargDamagesHourTract.*TractSunlightProfile(t_i,:)); %negative because we are subtracting

      if line_losses_loc==1
              marg_damages(t_i,1)=sum(-MargDamagesHourTract.*TractSunlightProfile(t_i,:).*(1+2.*alpha2LL(n_i,1).*(demand(:,n_i)'-ResProd(:,n_i)'))); %negative because we are subtracting
      end

end

marg_damages=marg_damages./1000; %convert back to kwh